package com.nari.ysphd.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import nari.mip.core.Platform;
import okhttp3.Call;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.Comm;
import com.nari.ysphd.MyApp;
import com.nari.ysphd.R;
import com.nari.ysphd.adapter.LocationAdapter;
import com.nari.ysphd.adapter.MeetingTypeAdapter;
import com.nari.ysphd.adapter.ResourceAdapter;
import com.nari.ysphd.adapter.isRecordAdapter;
import com.jeremyfeinstein.event.RefreshEvent;
import com.jeremyfeinstein.gson.DepItem;
import com.jeremyfeinstein.gson.Info;
import com.jeremyfeinstein.gson.InviteUser;
import com.jeremyfeinstein.gson.Location;
import com.jeremyfeinstein.gson.Meeting;
import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.gson.SelectItem;
import com.jeremyfeinstein.gson.UserItem;
import com.jeremyfeinstein.utils.DateFormatUtil;
import com.jeremyfeinstein.utils.DensityUtil;
import com.jeremyfeinstein.utils.ToastUtil;
import com.jeremyfeinstein.utils.YCHSInstance;
import com.jeremyfeinstein.utils.YCHShttpAPI;
import com.nari.ysphd.util.ActivityManager;
import com.nari.ysphd.util.Lengthwatch;
import com.nari.ysphd.view.DeptSelectDialog;
import com.nari.ysphd.view.ItemSelectDialog;
import com.nari.ysphd.view.MeetingUserDialog;

import de.greenrobot.event.EventBus;

public class MeetingManageUI extends BaseActivity implements OnClickListener {
    private static final String TAG = MeetingManageUI.class.getSimpleName();
    public static final String BUNDLE_MEETING_ID = "BUNDLE_MEETING_ID";
    private ProgressDialog progressDialog;
    private EditText room_name;
    private TextView room_company;
    private TextView room_hostname;
    private TextView room_assistant;
    private TextView room_date;
    private TextView room_enddate;
    private EditText room_summary;
    private EditText room_invitecode;
    private TextView meeting_manager_title;
    private View location_layout, networkInfoll;
    private Meeting meeting;
    private TextView activity_title;
    private String roomAssistant;
    private TextView invite_user;
    private TextView invite_user_id;
    private TextView is_record;
    private TextView meeting_type;
    private EditText meeting_numbers;
    private List<UserItem> userItems = null;
    private List<UserItem> inviteUsers = null;
    private TextView meeting_resource;
    private TextView location, networkInfo;
    private int meetingType;
    private int isRecord = 0;
    private String locationId;
    private int meetingResource;
    private Gson mGson;
    private String synNetwork;
    private String indexStr;
    private AlertDialog dialog;

    private List<DepItem> depItems;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGson = new GsonBuilder().create();
//        resetTime();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_meetingmanage);
    }

    @Override
    protected void onDestroy() {
//        remove();
        dismissDialog();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initViews() {
        activity_title = (TextView) findViewById(R.id.activity_title);
        //房间名称
        room_name = (EditText) findViewById(R.id.room_name);
        //组织单位
        room_company = (TextView) findViewById(R.id.room_company);
        //管理员
        room_hostname = (TextView) findViewById(R.id.room_creater);
        //助理
        room_assistant = (TextView) findViewById(R.id.room_assistant);
        //开始时间
        room_date = (TextView) findViewById(R.id.room_date);
        //结束时间
        room_enddate = (TextView) findViewById(R.id.room_enddate);
        //互动议程
        room_summary = (EditText) findViewById(R.id.room_summary);
        //互动口令
        room_invitecode = (EditText) findViewById(R.id.room_invitecode);
//		meeting_manager_title = (TextView) findViewById(R.id.meeting_manager_title);
        invite_user = (TextView) findViewById(R.id.invite_user);
        invite_user_id = (TextView) findViewById(R.id.invite_user_id);
        //类型
        meeting_type = (TextView) findViewById(R.id.meeting_type);
        //是否录制
//        is_record = (TextView) findViewById(R.id.is_record);
        meeting_resource = (TextView) findViewById(R.id.meeting_resource);
        //互动人数
        meeting_numbers = (EditText) findViewById(R.id.meeting_numbers);
        //变电站
        location_layout = findViewById(R.id.location_layout);
        //变电站
        location = (TextView) findViewById(R.id.location);
        //网点
        networkInfoll = findViewById(R.id.location2_layout);
        //网点
        networkInfo = (TextView) findViewById(R.id.netlocation);
    }


    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        showGoBackDialog(MeetingManageUI.this, "确定是否离开当前创建互动界面？", 1, 1);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            String meetingId = intent.getStringExtra(BUNDLE_MEETING_ID);
            getMeetingById(meetingId);

        }

        YCHShttpAPI.getUserInfo(getApplicationContext(), new StringCallback() {
            @Override
            public void onResponse(String response) {
                System.out.println("getUserInfo:" + response);
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    YCHSInstance.getInstance().setUserItems(onResponse.getUserInfoList());
                    updateViews();
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(MeetingManageUI.this, TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else {
//                    if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                        ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                        Platform.getCurrent().stop(getApplicationContext());
//                        ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                        return;
//                    }
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {

            }
        });
//        room_company.setHint("正在加载");
        YCHShttpAPI.getDepInfo(getApplicationContext(), new StringCallback() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "onResponse: " + response);
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
//                    room_company.setHint("加载完成");
                    depItems = onResponse.getDepInfoList();
//                    YCHSInstance.getApp().setDepItems(onResponse.getDepInfoList());
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(MeetingManageUI.this, TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else {
//                    if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                        ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                        Platform.getCurrent().stop(getApplicationContext());
//                        ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                        return;
//                    }
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
//                room_company.setHint("加载失败");
            }
        });


//        location.setHint("正在加载");
        YCHShttpAPI.GetResourceInfoList(this, "", new StringCallback() {
            @Override
            public void onResponse(String response) {
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
//                    location.setHint("加载完成");
                    YCHSInstance.getInstance().setLocations(onResponse.getResourceInfoList());
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(MeetingManageUI.this, TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
//                location.setHint("加载失败");
            }
        });


    }


    private void setMeetingData() {
        if (meeting == null || meeting.getMeetingId() == null) {
            activity_title.setText("创建互动");
            meeting = new Meeting();
          //  meeting.setHostName(YCHSInstance.getInstance().getLoginUser() == null ? "" : YCHSInstance.getInstance().getLoginUser().getUSER_NAME());
           // room_hostname.setText(meeting.getCreateName());
        } else {
            activity_title.setText("编辑互动");
            room_hostname.setText(meeting.getHostName());
            room_assistant.setText(meeting.getAssistantName());
            //编辑互动源不可编辑
            meeting_resource.setClickable(false);

            room_name.setText(meeting.getMeetingName());
            room_company.setText(meeting.getOrgName());
            room_date.setText(meeting.getStartTime());
            room_enddate.setText(meeting.getEndTime());
            room_summary.setText(meeting.getAgenda());
            room_invitecode.setText(meeting.getInvite_code());
            meeting_numbers.setText(meeting.getNumbers());


        }



        if ("0".equals(meeting.getMeetingType())) {
            meeting_type.setText("日常");
            meetingType = 0;
        }
        if ("1".equals(meeting.getMeetingType())) {
            meeting_type.setText("特殊");
            meetingType = 1;
        }

//        if ("0".equals(meeting.getIsRecord())) {
//            is_record.setText("否");
//            isRecord = 0;
//        }
//        if ("1".equals(meeting.getIsRecord())) {
//            is_record.setText("是");
//            isRecord = 1;
//        }

        if ("1".equals(meeting.getMeetingResource())) {
            meeting_resource.setText("网省");
            meetingResource = 1;
            networkInfoll.setVisibility(View.GONE);
            location_layout.setVisibility(View.VISIBLE);
            location.setText(meeting.getLocationName());
            locationId = meeting.getLocation();
            Log.e("meetingmanage", "location :" + meeting.getLocationName());
        }
        if ("2".equals(meeting.getMeetingResource())) {
            meeting_resource.setText("总部");
            meetingResource = 2;
            location_layout.setVisibility(View.GONE);
            networkInfoll.setVisibility(View.VISIBLE);
            networkInfo.setText(meeting.getNetworkName());
            Log.d("Meettingmanage", "NetWork :" + getnetwork(meeting.getSynNetwork()));
        }
        setInviteUser();
    }


    private String getnetwork(String key) {
        String network = "";
        String[] split = key.split(",");
        final List<Info> deviceInfos = YCHSInstance.getInstance().getInfos();
        if (deviceInfos == null || deviceInfos.size() == 0) {
            ToastUtil.showLong(MeetingManageUI.this, "获取网点信息失败!");
            return "";
        }
        for (Info info : deviceInfos) {
            for (int i = 0; i < split.length; i++) {
                if (split[i].equalsIgnoreCase(info.getID())) {
                    network += info.getNETWORK_NAME() + ",";
                }
            }
        }
        return network;

    }

    //将查询到的互动值放入
    private void setInviteUser() {
        List<InviteUser> iviteUsers = meeting.getInviterList();

        if (iviteUsers != null) {
            StringBuffer userIds = new StringBuffer(iviteUsers.size());
            StringBuffer userNames = new StringBuffer(iviteUsers.size());
            for (InviteUser user : iviteUsers) {
                userIds = userIds.append(user.getUserCode() + ",");
                userNames = userNames.append(user.getUserName() + ",");
            }
            invite_user.setText(userNames.toString());
            invite_user_id.setText(userIds.toString());
            userItems = YCHSInstance.getInstance().getUserItems();
        }

    }

    //根据互动id查询互动详情
    private void getMeetingById(String meetingId) {
        YCHShttpAPI.GetMeetingDetail(this, meetingId, new StringCallback() {
            @Override
            public void onError(Call call, int statusCode, Exception e) {
                showErrorWithStatus("获取互动信息出错！");
            }

            @Override
            public void onResponse(String response) {
                meeting = mGson.fromJson(response, Meeting.class);
                setMeetingData();

                YCHShttpAPI.getInfo(getApplicationContext(), new StringCallback() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("getInfo:" + response);
                        OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                        if ("0".equals(onResponse.getResultCode())) {
                            YCHSInstance.getInstance().setInfos(onResponse.getInfo());
                            if (meeting != null) {
                                //编辑
                                initNetworkInfo(meeting.getSynNetwork());
                            } else {
                                Log.e(TAG, "onResponse: meeting is null");
                            }
                        } else if ("1".equals(onResponse.getResultCode())) {
                            ToastUtil.showLong(MeetingManageUI.this, onResponse.getErrorMessage());
                        } else if ("-2".equals(onResponse.getResultCode())) {
                            Intent intent = new Intent(MeetingManageUI.this, TimeOutActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())) {
//                            ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                            Platform.getCurrent().stop(getApplicationContext());
//                            ToastUtil.showLong(MyApp.getApp(), onResponse.getErrorMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, int statusCode, Exception e) {
                        System.out.println("getInfo:" + e.getMessage());
                    }
                });
            }
        });
    }

    protected void updateViews() {
        if (meeting == null) {
            return;
        }
        room_assistant.setText(YCHSInstance.getInstance().getUserName(
                meeting.getAssistantCode()));
    }

    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void initNetworkInfo(String ids) {
        synNetwork = ids;
        if (ids == null) {
            return;
        }
        String[] infoidsStrings = ids.split(",");
        StringBuffer namesb = new StringBuffer();
        StringBuffer indexsb = new StringBuffer();
        List<Info> infos = YCHSInstance.getInstance().getInfos();
        if (infoidsStrings != null && infos != null) {
            for (int i = 0; i < infoidsStrings.length; i++) {
                for (int j = 0; j < infos.size(); j++) {
                    if (infoidsStrings[i].equals(infos.get(j).getID())) {
                        namesb.append(infos.get(j).getNETWORK_NAME() + ",");
                        indexsb.append(j + ",");
                    }
                }
            }
            networkInfo.setText(namesb);
            indexStr = indexsb.toString();
        } else {
            Log.e("jack", "initNetworkInfo: is null");
        }
    }

    @Override
    protected void initListeners() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.meetingmanage_back).setOnClickListener(this);
        findViewById(R.id.confirm_button).setOnClickListener(this);
        findViewById(R.id.cancel_button).setOnClickListener(this);
        room_date.setOnClickListener(this);
        room_enddate.setOnClickListener(this);
        room_company.setOnClickListener(this);
        room_hostname.setOnClickListener(this);
        room_assistant.setOnClickListener(this);
        invite_user.setOnClickListener(this);
        meeting_type.setOnClickListener(this);
        meeting_numbers.setOnClickListener(this);
        location.setOnClickListener(this);
//        is_record.setOnClickListener(this);
        meeting_resource.setOnClickListener(this);
        networkInfo.setOnClickListener(this);

        room_name.addTextChangedListener(new Lengthwatch(room_name, 64));
//        room_name.setFilters(new InputFilter[]{new inputFilter(MeetingManageUI.this, room_name, 3)});
//        room_summary.setFilters(new InputFilter[]{new inputFilter(MeetingManageUI.this, room_summary, 4)});
//        Comm.LegitimateInput(room_name, 1);

        InputFilter filter_space = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" "))
                    return "";
                else
                    return null;
            }
        };
        InputFilter filter_speChat = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                String speChat = "[`~!@#_$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）— +|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(charSequence.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };

        room_name.setFilters(new InputFilter[]{filter_space, filter_speChat});
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.room_company:
                if (depItems == null || depItems.size() == 0) {
                    ToastUtil.showToast("暂时没有获取到相应部门数据,请稍后再试!");
                } else {
                    final DeptSelectDialog deptSelectDialog = new DeptSelectDialog(MeetingManageUI.this, depItems);
                    deptSelectDialog.setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                            DepItem dept = (DepItem) parent.getAdapter().getItem(position);
                            room_company.setText(dept.getDEP_NAME());
                            meeting.setOrgId(dept.getID());
                            meeting.setOrgName(dept.getDEP_NAME());
                            deptSelectDialog.dismiss();
                        }
                    });
                    deptSelectDialog.showAsDropDown(room_company);
                }
                break;
            case R.id.room_creater:
                if (YCHSInstance.getInstance().getUserItems() == null
                        || YCHSInstance.getInstance().getUserItems().size() == 0) {
                    ToastUtil.showToast("暂时没有获取到相应管理人员的数据,请稍后再试!");
                }
                final MeetingUserDialog userSelect = new MeetingUserDialog(
                        MeetingManageUI.this, room_hostname.getText().toString().trim());
                userSelect.setWidth(room_hostname.getWidth());
                userSelect.setListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        UserItem user = (UserItem) parent.getAdapter().getItem(position);
                        room_hostname.setText(user.getUser_name());
                        meeting.setHostCode(user.getUser_code());
                        meeting.setHostName(user.getUser_name());
                        userSelect.dismiss();
                    }
                });
                userSelect.showAsDropDown(room_hostname, 0, DensityUtil.dip2px(this, 10));
                break;
            case R.id.room_assistant:
                if (YCHSInstance.getInstance().getUserItems() == null
                        || YCHSInstance.getInstance().getUserItems().size() == 0) {
                    ToastUtil.showToast("暂时没有获取到相应助理的数据,请稍后再试!");
                }
                final MeetingUserDialog assistantSelect = new MeetingUserDialog(
                        MeetingManageUI.this, room_assistant.getText().toString().trim());
                assistantSelect.setWidth(room_assistant.getWidth());
                assistantSelect.setListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        UserItem user = (UserItem) parent.getAdapter().getItem(position);
                        room_assistant.setText(user.getUser_name());
                        meeting.setAssistantCode(user.getUser_code());
                        meeting.setAssistantName(user.getUser_name());
                        assistantSelect.dismiss();
                    }
                });
                assistantSelect.showAsDropDown(room_assistant, 0, DensityUtil.dip2px(this, 10));
                break;
            case R.id.room_date:
                setDatePicker(room_date);
                break;
            case R.id.room_enddate:
                setDatePicker(room_enddate);
                break;
            case R.id.iv_back:
                showGoBackDialog(MeetingManageUI.this, "确定是否离开当前创建互动界面？", 1, 1);
//                finish();
                break;
            case R.id.meetingmanage_back:
                showGoBackDialog(MeetingManageUI.this, "确定是否离开当前创建互动界面？", 1, 1);
//                finish();
                break;
            case R.id.confirm_button:
                meetingManage();
                break;
            case R.id.cancel_button:
                clean();
                break;
            case R.id.invite_user:
                showInviteUserDialog();
                break;
            case R.id.meeting_type:
                showMeetingTypeDialog();
                break;
//            case R.id.is_record:
//                showRecordDialog();
//                break;
            case R.id.meeting_resource:
                showResourceDialog();
                break;
            case R.id.location:
                showLoationDialog();
                break;
            case R.id.netlocation:
                choiceNetworkDialog();
                break;
            default:
                break;
        }
    }

    private void showLoationDialog() {
        if (YCHSInstance.getInstance().getLocations() == null || YCHSInstance.getInstance().getLocations().size() == 0) {
            ToastUtil.showToast("暂时没有获取到相应变电站的数据,请稍后再试!");
            return;
        }
        final ItemSelectDialog locationSelect = new ItemSelectDialog(
                MeetingManageUI.this, location.getText().toString()
                .trim(), new LocationAdapter(this));
        locationSelect.setWidth(location.getWidth());
        locationSelect.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Location location1 = (Location) parent.getAdapter().getItem(position);
                location.setText(location1.getRESOURCE_NAME());
                locationId = location1.getOBJ_CODE();
                locationSelect.dismiss();
            }
        });
        locationSelect.showAsDropDown(location, 0, DensityUtil.dip2px(this, 10));
    }


    private void showResourceDialog() {
        final ItemSelectDialog resourceSelect = new ItemSelectDialog(
                MeetingManageUI.this, meeting_resource.getText().toString()
                .trim(), new ResourceAdapter(this));
        resourceSelect.setWidth(meeting_resource.getWidth());
        resourceSelect.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                SelectItem selectItem = (SelectItem) parent.getAdapter().getItem(position);
                if (2 == selectItem.getCode()) {
                    location_layout.setVisibility(View.GONE);
                    networkInfoll.setVisibility(View.VISIBLE);
                }
                if (1 == selectItem.getCode()) {
                    location_layout.setVisibility(View.VISIBLE);
                    networkInfoll.setVisibility(View.GONE);
                }
                meeting_resource.setText(selectItem.getName());
                meetingResource = selectItem.getCode();
                resourceSelect.dismiss();
            }
        });
        resourceSelect.showAsDropDown(meeting_resource, 0, DensityUtil.dip2px(this, 10));
    }

    private void showRecordDialog() {
        final ItemSelectDialog isReroadSelect = new ItemSelectDialog(
                MeetingManageUI.this, is_record.getText().toString()
                .trim(), new isRecordAdapter(this));
        isReroadSelect.setWidth(is_record.getWidth());
        isReroadSelect.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                SelectItem selectItem = (SelectItem) parent.getAdapter().getItem(position);
                is_record.setText(selectItem.getName());
                isRecord = selectItem.getCode();
                isReroadSelect.dismiss();
            }
        });
        isReroadSelect.showAsDropDown(is_record, 0, DensityUtil.dip2px(this, 10));
    }

    private void showMeetingTypeDialog() {
        final ItemSelectDialog typeSelect = new ItemSelectDialog(MeetingManageUI.this,
                meeting_type.getText().toString().trim(), new MeetingTypeAdapter(this));
        typeSelect.setWidth(meeting_type.getWidth());
        typeSelect.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SelectItem selectItem = (SelectItem) parent.getAdapter().getItem(position);
                meeting_type.setText(selectItem.getName());
                meetingType = selectItem.getCode();
                typeSelect.dismiss();
            }
        });
        typeSelect.showAsDropDown(meeting_type, 0, DensityUtil.dip2px(this, 10));
    }


    private HashMap<Integer, Boolean> selectedInviteUser = new HashMap<>();

    //展示可供选择的被邀请人
    private void showInviteUserDialog() {
        userItems = YCHSInstance.getInstance().getUserItems();
        if (userItems == null || userItems.size() == 0) {
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(MeetingManageUI.this);
        builder.setTitle("选择被邀请人");
        String[] userNames = new String[userItems.size()];
        String[] userCodes = new String[userItems.size()];
        for (int i = 0; i < userNames.length; i++) {
            userNames[i] = userItems.get(i).getUser_name();
            userCodes[i] = userItems.get(i).getUser_code();
        }
        final String[] InviteUserNameArray = userNames;
        final String[] InviteUserCodeArray = userCodes;
        boolean[] isSelected = new boolean[InviteUserNameArray.length];

        for (Map.Entry<Integer, Boolean> entry : selectedInviteUser.entrySet()) {
            if (!(entry.getKey() > isSelected.length)) {
                isSelected[entry.getKey()] = entry.getValue();
            }
        }

        // 设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉多选框的数据集合
         * 第二个参数代表哪几个选项被选择，如果是null，则表示一个都不选择，如果希望指定哪一个多选选项框被选择，
         * 需要传递一个boolean[]数组进去，其长度要和第一个参数的长度相同，例如 {true, false, false, true};
         * 第三个参数给每一个多选项绑定一个监听器
         */
        builder.setMultiChoiceItems(InviteUserNameArray, isSelected,
                new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        selectedInviteUser.put(which, isChecked);
                    }
                });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                StringBuffer sb = new StringBuffer(InviteUserNameArray.length);
                StringBuffer indexsb = new StringBuffer(InviteUserNameArray.length);
                for (Map.Entry<Integer, Boolean> entry : selectedInviteUser.entrySet()) {
                    if (entry.getValue()) {
                        sb.append(InviteUserNameArray[entry.getKey()] + ", ");
                        indexsb.append(InviteUserCodeArray[entry.getKey()] + ",");
                    }
                }
                invite_user.setText(sb.toString());
                invite_user_id.setText(indexsb.toString());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               /* selectedInviteUser.clear();
                invite_user.setText("");
                invite_user_id.setText("");*/

            }
        });
        builder.show().create();
    }

    protected void meetingManage() {
        String roomName = room_name.getText().toString();
        String roomCompany = null;
        String roomCreater = null;
        if (meeting != null) {
            roomCompany = meeting.getOrgId();
            roomCreater = meeting.getHostCode();
        }
        String assistant = room_assistant.getText().toString();
        if (TextUtils.isEmpty(assistant)) {
            roomAssistant = null;
        } else {
            if (meeting != null) {
                roomAssistant = meeting.getAssistantCode();
            }
        }
        String meetingTypeText = meeting_type.getText().toString();
        String meetingResourceText = meeting_resource.getText().toString();
        String roomStartTime = room_date.getText().toString();
        String roomEndTime = room_enddate.getText().toString();
        String roomSummary = room_summary.getText().toString();
        String roomInvitecode = room_invitecode.getText().toString();
        String networkInfoContent = networkInfo.getText().toString();

        String invitedUsers = getInviteUsers();
        String numbers = meeting_numbers.getText().toString();

       /* if (TextUtils.isEmpty(roomName) || TextUtils.isEmpty(roomCreater)
                || TextUtils.isEmpty(roomStartTime)
                || TextUtils.isEmpty(roomEndTime)
                || TextUtils.isEmpty(roomSummary)
                || TextUtils.isEmpty(roomInvitecode)
                || TextUtils.isEmpty(roomCompany)
                || TextUtils.isEmpty(getText())
                || -1 == meetingType) {
            showErrorWithStatus("请填写完整!");
            return;
        }*/

        if (TextUtils.isEmpty(roomName)) {
            showErrorWithStatus("请填写互动名称!");
            return;
        }
        if (TextUtils.isEmpty(roomCompany)) {
            showErrorWithStatus("请填写组织单位！");
            return;
        }
        if (TextUtils.isEmpty(roomCreater)) {
            showErrorWithStatus("请选择管理员！");
            return;
        }
        if (TextUtils.isEmpty(roomStartTime)) {
            showErrorWithStatus("请选择互动开始时间！");
            return;
        }
        if (TextUtils.isEmpty(roomEndTime)) {
            showErrorWithStatus("请选择互动结束时间！");
            return;
        }

        if (TextUtils.isEmpty(numbers)) {
            showErrorWithStatus("请输入互动人数!");
            return;
        }

        if (TextUtils.isEmpty(meetingTypeText)) {
            showErrorWithStatus("请选择互动类型!");
            return;
        }

        if (TextUtils.isEmpty(roomInvitecode)) {
            showErrorWithStatus("请填写互动邀请码！");
            return;
        }

        if (TextUtils.isEmpty(meetingResourceText)) {
            showErrorWithStatus("请填写互动来源");
            return;
        }

        if (location_layout.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(locationId)) {
                showErrorWithStatus("请选择变电站!");
                return;
            }
        }


        if (TextUtils.isEmpty(roomSummary)) {
            showErrorWithStatus("请填写互动议程！");
            return;
        }

        if (Comm.IsLegitimate(roomName, true)) {
            showErrorWithStatus("互动名称含义非法字符，请按照规范填写内容！");
            return;
        }

        if (Comm.IsLegitimate(roomSummary, false)) {
            showErrorWithStatus("互动议程含有非法字符，请按照规范填写内容！");
            return;
        }

        if (Integer.valueOf(numbers) < 2 || Integer.valueOf(numbers) > 100) {
            showErrorWithStatus("互动人数应该在2到100人！");
            return;
        }

        progressDialog = ProgressDialog.show(this, null, "正在加载...");

        YCHShttpAPI.meetingManager(this, meeting.getMeetingId(), roomName,
                roomCreater, roomInvitecode, roomStartTime, roomEndTime,
                roomCompany, roomSummary, meetingResource, roomAssistant,
                isRecord, invitedUsers, meetingType, locationId, numbers, meeting.getUpdateTime(), synNetwork, new StringCallback() {
                    @Override
                    public void onResponse(String response) {
                        dismissDialog();
                        System.out.println("meetingManager response:" + response);
                        OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                        if ("0".equals(onResponse.getResultCode())) {
                            if (meeting == null || meeting.getMeetingId() == null) {
                                showGoBackDialog(MeetingManageUI.this, "创建互动成功!", 2, 2);
                            } else {
                                showTaskDialog(MeetingManageUI.this);
                            }
                        } else if ("-2".equals(onResponse.getResultCode())) {
                            Intent intent = new Intent(MeetingManageUI.this, TimeOutActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else {
//                            if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                                ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                                Platform.getCurrent().stop(getApplicationContext());
//                                ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                                return;
//                            }
                            showErrorWithStatus(onResponse.getErrorMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, int statusCode, Exception e) {
                        Log.e("meeting", "exception:" + e.getMessage());
                        dismissDialog();
                    }
                });

    }

    private String getText() {
        if (meetingResource == 1) {
            return location.getText().toString();
        }
        return networkInfo.getText().toString();
    }

    //将被邀请人发送到到后台以'[{"name":"123","code":"1234"},{"name":"测试用户09","code":"016"}]'格式
    private String getInviteUsers() {
        String indexs;
        userItems = YCHSInstance.getInstance().getUserItems();
        if (invite_user_id.getText() != null) {
            indexs = invite_user_id.getText().toString();
            String codeArray[] = indexs.split(",");
            inviteUsers = new ArrayList<>();
            for (int i = 0; i < codeArray.length; i++) {
                if (userItems != null) {
                    for (UserItem user : userItems) {
                        if (codeArray[i].equals(user.getUser_code())) {
                            inviteUsers.add(user);
                            break;
                        }
                    }
                }
            }
            return mGson.toJson(inviteUsers);
        }
        return "";
    }

    private void setDatePicker(final TextView tv) {
        String dateString = tv.getText().toString();
        Date date = new Date();
        if (!TextUtils.isEmpty(dateString)) {
            date = DateFormatUtil.parseDateFromString(dateString);
        }
        DateTimePickerDialog d = new DateTimePickerDialog(this, date.getTime());
        d.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            public void OnDateTimeSet(AlertDialog dialog, long date) {
                Calendar mDate = Calendar.getInstance();
                mDate.setTimeInMillis(date);
                mDate.set(Calendar.SECOND, 0);
                String dateFormate = DateFormatUtil.millisToLongDate(date);
                Log.e("EndTime", dateFormate);
                tv.setText(dateFormate);
            }
        });
        d.show();
    }

    private void showTaskDialog(final Context mContext) {
        if (!((Activity) mContext).isFinishing()) {
            if (dialog != null && dialog.isShowing()) {
                return;
            }
            //show dialog
            dialog = new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false).setMessage("修改互动成功!")
                    .setNeutralButton("继续修改", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            initData();
                        }
                    })
                    .setNegativeButton("返回列表", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(new RefreshEvent());
                            showSuccessWithStatus(activity_title.getText().toString() + "成功");
                            finish();
                        }
                    })
                    .create();

            if (!(mContext instanceof Activity)) {
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
            dialog.show();
        }
    }

    protected void clean() {
        room_name.setText("");
        room_company.setText("");
        room_hostname.setText("");
        room_assistant.setText("");
        room_date.setText("");
        room_enddate.setText("");
        room_summary.setText("");
        room_invitecode.setText("");
        invite_user.setText("");
        invite_user_id.setText("");
        meeting_type.setText("");
        meeting_numbers.setText("");
        meeting_resource.setText("");
        is_record.setText("");
        networkInfo.setText("");
    }

    // 选择设备对话框
    private void choiceNetworkDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MeetingManageUI.this);
        builder.setTitle("网点信息");
        final List<Info> deviceInfos = YCHSInstance.getInstance().getInfos();
        if (deviceInfos == null || deviceInfos.size() == 0) {
            ToastUtil.showLong(MeetingManageUI.this, "获取网点信息失败!");
            return;
        }
        //将上次选的值记忆下来
        String checkedItemIdex = null;
        if (!TextUtils.isEmpty(synNetwork)) {
            checkedItemIdex = indexStr;
        }
        boolean[] checkedArray = new boolean[deviceInfos.size()];
        String[] names = new String[deviceInfos.size()];
        final String[] ids = new String[deviceInfos.size()];
        for (int i = 0; i < names.length; i++) {
            names[i] = deviceInfos.get(i).getNETWORK_NAME();
            ids[i] = deviceInfos.get(i).getID();
            checkedArray[i] = false;
        }

        //将选中的放进数组
        if (checkedItemIdex != null) {
            String[] indexArray = checkedItemIdex.split(",");
            for (int i = 0; i < indexArray.length; i++) {
                checkedArray[Integer.parseInt(indexArray[i])] = true;
            }
        }
        final String[] devNmArray = names;
        // 设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉多选框的数据集合
         * 第二个参数代表哪几个选项被选择，如果是null，则表示一个都不选择，如果希望指定哪一个多选选项框被选择，
         * 需要传递一个boolean[]数组进去，其长度要和第一个参数的长度相同，例如 {true, false, false, true};
         * 第三个参数给每一个多选项绑定一个监听器
         */
        builder.setMultiChoiceItems(devNmArray, checkedArray, new DialogInterface.OnMultiChoiceClickListener() {
            StringBuffer sb = new StringBuffer(100);
            StringBuffer idsb = new StringBuffer(100);
            StringBuffer indexsb = new StringBuffer(100);

            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked) {
                    sb.append(devNmArray[which] + ", ");
                    idsb.append(ids[which] + ",");
                    indexsb.append(which + ",");
                }
                synNetwork = idsb.toString();
                indexStr = indexsb.toString();
                networkInfo.setText(sb.toString());
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                synNetwork = "";
                indexStr = "";
                networkInfo.setText("");
            }
        });
        builder.show();
    }

    public void showGoBackDialog(final Context mContext, String str, final int mode, final int code) {
        if (!((Activity) mContext).isFinishing()) {
            if (dialog != null && dialog.isShowing()) {
                return;
            }
            if (mode == 1) {
                dialog = new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false).setMessage(str)
                        .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (code == 1) {
                                    ((Activity) mContext).finish();
                                } else if (code == 2) {
                                    EventBus.getDefault().post(new RefreshEvent());
                                    showSuccessWithStatus(activity_title.getText().toString() + "成功");
                                    finish();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
            } else if (mode == 2) {
                dialog = new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false).setMessage(str)
                        .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (code == 1) {
                                    ((Activity) mContext).finish();
                                } else if (code == 2) {
                                    EventBus.getDefault().post(new RefreshEvent());
                                    showSuccessWithStatus(activity_title.getText().toString() + "成功");
                                    finish();
                                }
                            }
                        }).create();
            }


            if (!(mContext instanceof Activity)) {
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
            dialog.show();
        }
    }


}
